<template>
  <div class="user-container">
    <el-row class="container-row">
      <!-- 侧边栏 -->
      <el-col :span="4" class="sidebar">
        <div class="sidebar-header">
          <h2>功能菜单</h2>
        </div>
        <el-menu 
          default-active="1" 
          class="el-menu-vertical-demo"
          @select="handleMenuSelect"
        >
          <el-menu-item index="1">
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="2">
            <span>就餐数据</span>
          </el-menu-item>
        </el-menu>
      </el-col>

      <!-- 主内容区 -->
      <el-col :span="20" class="main-content">
        <div class="toolbar">
          <span class="page-title">{{ currentPageTitle }}</span>
          <el-button 
            type="danger" 
            @click="handleLogout"
          >
            退出登录
          </el-button>
        </div>

        <div class="page-content">
          <!-- 个人信息页 -->
          <template v-if="currentPage === 'personal'">
            <el-card title="个人信息">
              <div class="btn-group">
                <el-button v-if="!isEditMode" type="primary" @click="enterEditMode">
                  修改基本信息
                </el-button>
                <el-button v-if="isEditMode" type="primary" @click="handleSaveBaseInfo">
                  保存信息
                </el-button>
                <el-button v-if="isEditMode" @click="cancelEdit">
                  取消
                </el-button>
                <el-button type="warning" @click="openPasswordDialog">
                  修改密码
                </el-button>
              </div>

              <el-form 
                :model="teacherInfo" 
                :rules="baseInfoRules" 
                ref="baseInfoFormRef"
                label-width="120px"
                class="teacher-form"
              >
                <el-form-item label="工号" prop="teacherId">
                  <el-input v-model="teacherInfo.teacherId" disabled />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="teacherInfo.name" :disabled="!isEditMode" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="teacherInfo.gender" placeholder="请选择性别" :disabled="!isEditMode">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="department">
                  <el-input v-model="teacherInfo.department" :disabled="!isEditMode" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="teacherInfo.phone" :disabled="!isEditMode" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="teacherInfo.email" type="email" :disabled="!isEditMode" />
                </el-form-item>
              </el-form>
            </el-card>
          </template>

          <!-- 就餐数据页 -->
          <template v-if="currentPage === 'dining'">
            <el-card title="就餐记录管理">
              <!-- 加载状态 -->
              <el-skeleton v-if="loading" :rows="5" style="margin-top: 20px;" />

              <!-- 就餐记录表格 -->
              <el-table 
                v-else 
                :data="diningRecordList" 
                border 
                style="width: 100%; margin-top: 20px;"
                empty-text="暂无就餐记录数据"
              >
                <el-table-column prop="recordId" label="记录ID" align="center" width="100" />
                <el-table-column prop="diningTime" label="就餐时间" align="center" width="200" />
                <el-table-column prop="merchantName" label="商户名称" align="center" width="180" />
                <el-table-column prop="amount" label="消费金额" align="center" width="120">
                  <template #default="scope">
                    {{ scope.row.amount.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="subsidy" label="补贴金额" align="center" width="120">
                  <template #default="scope">
                    {{ (scope.row.subsidy || 0).toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column prop="paymentMethod" label="支付方式" align="center" width="150">
                  <template #default="scope">
                    <el-tag :type="getPaymentMethodTagType(scope.row.paymentMethod)">
                      {{ getPaymentMethodText(scope.row.paymentMethod) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" align="center" width="120">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                      {{ scope.row.status === 1 ? '已完成' : '对账中' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </template>
        </div>
      </el-col>
    </el-row>

    <!-- 密码修改弹窗 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="120px"
        class="password-form"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码（6-20位，包含数字和字母）" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确定修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElForm, type FormRules, ElMessageBox, ElSkeleton, ElTag } from 'element-plus';
import request from '@/utils/request';
import type { Teacher, ChangePasswordRequest, DiningRecord } from '@/types/index';

const router = useRouter();

// 页面状态管理
const currentPage = ref('personal');
const currentPageTitle = ref('个人信息');
const baseInfoFormRef = ref<InstanceType<typeof ElForm>>();
const isEditMode = ref(false);
const loading = ref(false);

// 教师基本信息数据
const teacherInfo = reactive<Teacher>({
  teacherId: '',
  name: '',
  gender: '',
  department: '',
  phone: '',
  email: '',
  status: 1
});

// 基本信息验证规则
const baseInfoRules: FormRules<Teacher> = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' },
    { max: 100, message: '部门名称不能超过100个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

// 密码修改相关状态
const passwordDialogVisible = ref(false);
const passwordFormRef = ref<InstanceType<typeof ElForm>>();

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const passwordRules = reactive<FormRules<typeof passwordForm>>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为 6-20 个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[A-Za-z])(?=.*\d).+$/, 
      message: '密码必须包含字母和数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// --- 就餐记录相关代码 ---
const diningRecordList = ref<DiningRecord[]>([]);

// 获取就餐记录列表
// 修改 getDiningRecordList 中获取工号的代码
const getDiningRecordList = async () => {
  loading.value = true;
  try {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      throw new Error('未找到用户信息，请先登录');
    }
    const user = JSON.parse(userStr);
    console.log('localStorage中的用户信息:', user); // 已确认有 workId 字段

    // 关键修正：使用正确的字段名 workId（小写w）
    const teacherId = user.workId; 

    // 验证工号是否有效
    if (!teacherId || teacherId.trim() === '') {
      throw new Error('用户信息不完整，工号为空');
    }

    // 发起请求
    const response = await request.get(
      `/api/DapperDemo/dining-records/with-details?teacherId=${teacherId}`
    );

    // 解析响应（后端直接返回 {message, data}）
    const backendResponse = response.data;
    const diningRecords = backendResponse.data;

    if (Array.isArray(diningRecords)) {
      diningRecordList.value = diningRecords;
      ElMessage.success(`成功加载 ${diningRecords.length} 条就餐记录`);
    } else {
      throw new Error('后端返回的 data 不是数组');
    }
  } catch (error: any) {
    console.error('获取就餐记录失败:', error);
    ElMessage.error('加载就餐记录失败：' + (error.message || '未知错误'));
    diningRecordList.value = [];
  } finally {
    loading.value = false;
  }
};
// 辅助方法：转换支付方式为文本
const getPaymentMethodText = (method: number | undefined) => {
  switch(method) {
    case 1: return '食堂卡';
    case 2: return '微信支付';
    case 3: return '支付宝';
    default: return '未知方式';
  }
};

// 辅助方法：设置支付方式标签类型（修复ElTag类型错误）
const getPaymentMethodTagType = (method: number | undefined) => {
  switch(method) {
    case 1: return 'primary';
    case 2: return 'success';
    case 3: return 'info';
    default: return 'warning'; // 将default改为warning（Element Plus支持的类型）
  }
};

// --- 菜单切换与个人信息方法 ---
const handleMenuSelect = (index: string) => {
  switch(index) {
    case '1':
      currentPage.value = 'personal';
      currentPageTitle.value = '个人信息';
      break;
    case '2':
      currentPage.value = 'dining';
      currentPageTitle.value = '就餐记录管理';
      getDiningRecordList();
      break;
  }
};

const enterEditMode = () => {
  isEditMode.value = true;
};

const cancelEdit = () => {
  isEditMode.value = false;
  getTeacherInfo();
};

const openPasswordDialog = () => {
  passwordForm.oldPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  passwordFormRef.value?.clearValidate();
  passwordDialogVisible.value = true;
};

const getTeacherInfo = async () => {
  loading.value = true;
  try {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      throw new Error('未找到用户信息');
    }
    const user = JSON.parse(userStr);
    const teacherId = user.workId;
    
    if (!teacherId) {
      throw new Error('未获取到工号');
    }

    const res = await request.get<Teacher>(`/api/Teacher/${teacherId}`);
    Object.assign(teacherInfo, res);
  } catch (error: any) {
    console.error('获取个人信息失败:', error);
    ElMessage.error(`获取个人信息失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

const handleSaveBaseInfo = async () => {
  if (!baseInfoFormRef.value) return;

  try {
    await baseInfoFormRef.value.validate();
    
    const baseData: Partial<Teacher> = {
      teacherId: teacherInfo.teacherId,
      name: teacherInfo.name,
      gender: teacherInfo.gender,
      department: teacherInfo.department,
      phone: teacherInfo.phone,
      email: teacherInfo.email,
      status: teacherInfo.status
    };

    await request.put(`/api/Teacher/${teacherInfo.teacherId}`, baseData);

    const userStr = localStorage.getItem('user');
    if (userStr) {
      const user = JSON.parse(userStr);
      user.userName = teacherInfo.name;
      localStorage.setItem('user', JSON.stringify(user));
    }

    ElMessage.success('个人信息修改成功');
    isEditMode.value = false;
  } catch (error: any) {
    if (!error.message.includes('Token 已过期')) {
      ElMessage.error(error.message || '保存失败，请检查输入');
    }
  }
};

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    
    const passwordData: ChangePasswordRequest = {
      WorkId: teacherInfo.teacherId,
      OldPassword: passwordForm.oldPassword,
      NewPassword: passwordForm.newPassword
    };
    
    await request.post('/api/Auth/change-password', passwordData);
    ElMessage.success('密码修改成功，请重新登录');
    
    passwordDialogVisible.value = false;
    handleLogout();
  } catch (error: any) {
    ElMessage.error(error.message || '密码修改失败');
  }
};

const handleLogout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  router.push('/login');
  ElMessage.success('已成功退出登录');
};

onMounted(() => {
  getTeacherInfo();
});
</script>

<style scoped>
/* 样式保持不变 */
.user-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.container-row {
  height: 100%;
}

.sidebar {
  height: 100%;
  background-color: #2c3e50;
  color: #fff;
  padding-top: 20px;
}

.sidebar-header {
  text-align: center;
  padding: 0 20px 20px;
  border-bottom: 1px solid #47637e;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.el-menu-vertical-demo {
  background-color: transparent;
  border-right: none;
}

.el-menu-item {
  color: #ecf0f1;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.el-menu-item:hover, .el-menu-item.is-active {
  background-color: #34495e;
  color: #409eff;
}

.main-content {
  height: 100%;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eaecef;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.page-content {
  padding: 20px;
}

.btn-group, .operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.operation-bar {
  justify-content: flex-end;
}

.teacher-form, .dish-form, .password-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.empty-page {
  text-align: center;
  padding: 80px 0;
}
</style>